//
//  ScanDeviceViewController.m
//  DTSTON
//
//  Created by 喻贵华 on 16/5/5.
//  Copyright © 2016年 Demo. All rights reserved.
//
#import "BindDeviceApi.h"
#import "ScanfQRCodeView.h"
#import "ScanDeviceViewController.h"
#import "UIColor+HEX.h"
#import "MBProgressHUD.h"
//#import "AddDeviceByCodeViewController.h"
#import "BindDeviceApi.h"
#import "GetUserDeviceApi.h"
#import "BindHuanxinGroupIdApi.h"

@interface ScanDeviceViewController()<ScanfQRCodeViewDelegate>

@property (strong, nonatomic) UIImageView *scanImageView;

@property (strong, nonatomic) UIView *bgView;
@property (strong, nonatomic) UIImageView *line;
@property (strong, nonatomic) UILabel *label;
@property (strong, nonatomic) UIButton *SerialNumberBtn;
@property (strong, nonatomic) UILabel *tipslabel;


//- (IBAction)goToAddDevice:(UIButton *)sender;
@end
@implementation ScanDeviceViewController
{
    
    ScanfQRCodeView *scanfView_;
}
-(void)viewDidLoad
{
    [super viewDidLoad];
    [self setNavigationBarTitle:@"扫码绑定"];
//    [self setLeftButtonImage:[UIImage imageNamed:@"nav_icon_return"]];
    self.view.backgroundColor=[UIColor blackColor];
    scanfView_ = [[ScanfQRCodeView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    scanfView_.delegate = self;
    
    [self HUD];
    
    [self.view addSubview:scanfView_];
    [self.view sendSubviewToBack:scanfView_];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
         [self animationForLine];
    });
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    [scanfView_ stopRunning];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
}


-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.navigationController setNavigationBarHidden:NO];//这句如果设成Yes会导致侧滑失效
    [self.navigationController.navigationBar setHidden:YES];

    
    [scanfView_ startScan];
    
    [self bgView];
    [self line];
    //启动动画
}

- (void)HUD
{
    MBProgressHUD *HUD =[[MBProgressHUD alloc]initWithView:self.view];
    [self.view addSubview:HUD];
    //如果设置此属性则当前的view置于后台
    HUD.dimBackground = YES;
    //设置对话框文字
    HUD.labelText = @"正在加载";
    //显示对话框
    [HUD showAnimated:YES whileExecutingBlock:^{
        //对话框显示时需要执行的操作
        sleep(1.f);
    } completionBlock:^{
        //操作执行完后取消对话框
        [HUD removeFromSuperview];
    }];
}


#pragma mark -- 点击事件
- (void)didClickSerialButton
{
//    UIStoryboard* mainStoryboard = [UIStoryboard storyboardWithName:@"UserMain" bundle:nil];
//    AddDeviceByCodeViewController *vc = [AddDeviceByCodeViewController new];
//    [self.navigationController pushViewController:vc animated:YES];
}

- (UIImageView *)line
{
    if (!_line) {
        _line = [[UIImageView alloc]initWithFrame:CGRectMake(30, 0, self.scanImageView.frame.size.width - 60, 5)];
//        [_line setImage:[UIImage imageNamed:@"scan_line"]];
        [self.scanImageView addSubview:_line];
    }
    return _line;
}

- (UIView *)bgView
{
    if (!_bgView) {
        // 这里创建指引在这个视图在window上
        CGRect frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64);//[UIScreen mainScreen].bounds;
        UIView * bgView = [[UIView alloc]initWithFrame:frame];
        _bgView = bgView;
        bgView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.65];
        [self.view addSubview:bgView];
        
        //create path 重点来了（**这里需要添加第一个路径）
        UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
        [path appendPath:[[UIBezierPath bezierPathWithRoundedRect:CGRectMake(self.scanImageView.frame.origin.x, self.scanImageView.frame.origin.y - 64, self.scanImageView.frame.size.width, self.scanImageView.frame.size.height) cornerRadius:0] bezierPathByReversingPath]];
        
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.path = path.CGPath;
        [bgView.layer setMask:shapeLayer];
        [self.view bringSubviewToFront:self.label];
        [self.view bringSubviewToFront:self.SerialNumberBtn];
        [self.view bringSubviewToFront:self.tipslabel];
    }
    return _bgView;
}

- (void) scanfQRCode:(ScanfQRCodeView *)scanfview result:(NSString *)result{
    
    [self pauseAnimation];
    [SVProgressHUD showWithStatus:@"正在绑定中..."];
//    if ([result isNumberString] && result.length == 15) {//DH:ACCF2353451A:202
        BindDeviceApi *api = [[BindDeviceApi alloc]initWithDic:@{@"sn":result}];
        [api dtDefaultInterceptStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
            [SVProgressHUD showInfoWithStatus:request.responseObject[@"errmsg"]];
            NSDictionary *dict = request.responseJSONObject;
            SAVE_OBJECT(dict[@"gid"], GID);
            SAVE_OBJECT(dict[@"device_id"], DEVICEID);
            SAVE_OBJECT(result, DEVICEMAC);
            [[DataManager sharedInstance] subscribeTheme];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popToRootViewControllerAnimated:YES];
            });
//            if ([dict[@"admin_uid"] isEqualToString:EXRACT_OBJECT(UID)])
//            {
//                [self addGroup];
//            }
//            else
//            {
//                [self joinGroup];
//            }
//            [self getUserDevice];
//            [self.navigationController popViewControllerAnimated:YES];
        } failure:^(YTKBaseRequest * _Nonnull request) {
//            dispatch_sync(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:[request responseJSONObject][@"errmsg"]];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [scanfView_ startScan];
                [self startAnimation];
            });
//            });

        }];
        
//    }else{
//        [SVProgressHUD showErrorWithStatus:@"二维码格式不正确"];

//        [[AlertViewManager shareManager] initWithMessage:@"二维码格式不正确" cancleButtonTitle:@"确定" clickAtIndex:^(NSInteger buttonIndex, UIAlertController *alertController) {
//
//        }];
//    }
}



- (void)pauseAnimation
{
    CFTimeInterval pauseTime = [self.line.layer convertTime:CACurrentMediaTime() fromLayer:nil];
    self.line.layer.timeOffset = pauseTime;
    self.line.layer.speed = 0;
}

- (void)startAnimation
{
    // 时间转换
    CFTimeInterval pauseTime = self.line.layer.timeOffset;
    // 计算暂停时间
    CFTimeInterval timeSincePause = CACurrentMediaTime() - pauseTime;
    // 取消
    self.line.layer.timeOffset = 0;
    // local time相对于parent time世界的beginTime
    self.line.layer.beginTime = timeSincePause;
    // 继续
    self.line.layer.speed = 1;
}

- (void)animationForLine
{
    [UIView animateWithDuration:2 delay:0 options:UIViewAnimationOptionRepeat animations:^{
        _line.center = CGPointMake(_line.center.x, self.scanImageView.frame.size.height);
    } completion:nil];
}


//- (void)getUserDevice
//{
//    GetUserDeviceApi *api = [[GetUserDeviceApi alloc] init];
//    [api dtStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
//        NSString *deviceID = [request responseJSONObject][@"data"][@"device_id"];
//        SAVE_OBJECT(deviceID, DEVICEID);
//        [self.navigationController popToRootViewControllerAnimated:YES];
//    } failure:nil];
//}

#pragma mark --- 群组
- (void)addGroup
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        EMGroupOptions *setting = [[EMGroupOptions alloc] init];
        setting.maxUsersCount = 200;
        setting.style = EMGroupStylePublicOpenJoin;
        EMError *error = nil;
        EMGroup *group = [[EMClient sharedClient].groupManager createGroupWithSubject:@"小天机器人" description:@"我的家人" invitees:nil message:nil setting:setting error:&error];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (group && !error)
            {
                SAVE_OBJECT(group.groupId, GID);
                [self bindHuanXinGroupID];
            }
            else
            {
                [self addGroup];
            }
        });
    });
}

- (void)joinGroup
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        EMGroupOptions *setting = [[EMGroupOptions alloc] init];
        setting.maxUsersCount = 200;
        setting.style = EMGroupStylePublicOpenJoin;
        EMError *error = nil;
        EMGroup *group = [[EMClient sharedClient].groupManager joinPublicGroup:EXRACT_OBJECT(GID) error:&error];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (group && !error)
            {
                [SVProgressHUD showSuccessWithStatus:@"绑定成功"];
                [self.navigationController popToRootViewControllerAnimated:YES];
            }
            else
            {
                if ((error.code = EMErrorGroupAlreadyJoined))
                {
                    [SVProgressHUD showSuccessWithStatus:@"绑定成功"];
                    [self.navigationController popToRootViewControllerAnimated:YES];
                    return;
                }
                [self joinGroup];
            }
        });
    });
}

- (void)bindHuanXinGroupID
{
    BindHuanxinGroupIdApi *api = [[BindHuanxinGroupIdApi alloc] initWithDic:@{@"device_id":EXRACT_OBJECT(DEVICEID),@"gid":EXRACT_OBJECT(GID)}];
    [api dtStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showSuccessWithStatus:@"绑定成功"];
            [self.navigationController popToRootViewControllerAnimated:YES];
        });

    } failure:nil];
}

#pragma mark --- 懒加载
- (UIImageView *)scanImageView
{
    if(!_scanImageView)
    {
        UIView *superView = self.view;
        _scanImageView = [[UIImageView alloc]init];
        [superView addSubview:_scanImageView];
        _scanImageView.image = [UIImage imageNamed:@"scan_base_frame"];
    }
    return _scanImageView;
}
- (UILabel *)label
{
    if(!_label)
    {
        UIView *superView = self.view;
        _label = [[UILabel alloc]init];
        [superView addSubview:_label];
        [_label setFont:fontWithSize(15)];
        [_label setTextColor:[UIColor whiteColor]];
        _label.text = @"将二维码放在识别框中";
    }
    return _label;
}
- (UIButton *)SerialNumberBtn
{
    if(!_SerialNumberBtn)
    {
        UIView *superView = self.view;
        _SerialNumberBtn = [[UIButton alloc]init];
        [superView addSubview:_SerialNumberBtn];
        [_SerialNumberBtn setTitle:@"输入序列号绑定" forState:UIControlStateNormal];
        [_SerialNumberBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        [_SerialNumberBtn setBackgroundImage:imageWithName(@"but_serial_nor") forState:UIControlStateNormal];
        [_SerialNumberBtn addTarget:self action:@selector(didClickSerialButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _SerialNumberBtn;
}

- (UILabel *)tipslabel
{
    if(!_tipslabel)
    {
        UIView *superView = self.view;
        _tipslabel = [[UILabel alloc]init];
        [superView addSubview:_tipslabel];
        [_tipslabel setFont:fontWithSize(15)];
        [_tipslabel setTextColor:[UIColor whiteColor]];
        _tipslabel.text = @"二维码扫描不成功？请点此";
    }
    return _tipslabel;
}

- (void)masLayoutSubview
{
    __weak UIView *superView = self.view;
    
    [self.scanImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(superView);
    }];
    
    [self.label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.scanImageView.mas_bottom).with.offset(px1920Height(30));
        make.centerX.mas_equalTo(superView.mas_centerX);
    }];
    
//    [self.SerialNumberBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.mas_equalTo(superView.mas_centerX);
//        make.bottom.mas_equalTo(self.tipslabel.mas_top).with.offset(-px1920Height(50));
//    }];
//    
//    [self.tipslabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.mas_equalTo(superView.mas_centerX);
//        make.bottom.mas_equalTo(superView.mas_bottom).with.offset(-px1920Height(50));
//    }];
}

@end
